<?php

namespace App\Filament\User\Pages;

use Filament\Forms\Components\Component;
use Filament\Forms\Components\TextInput;
use Filament\Pages\Auth\Register as BaseRegister;
use Illuminate\Contracts\Support\Htmlable;
use Livewire\Attributes\Url;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;
use App\Models\Referral;
use App\Models\User;


class Register extends BaseRegister
{
     #[Url]
     public $refer = "";
     public function mount(): void
     {
         parent::mount();

         if(!Cookie::get('refer') && request()->query('refer')){
             Cookie::queue('refer', $this->refer, 60*30);
         }else{
             $this->refer = Cookie::get('refer');
         }
     }

    public function getTitle(): string | Htmlable
    {
        return '前端组件库-注册账号';
    }

    public function getHeading(): string|Htmlable
    {
        return "前端组件库";
    }

    protected function getForms(): array
    {
        return [
            'form' => $this->form(
                $this->makeForm()
                    ->schema([
                        $this->getNameFormComponent(),
                        $this->getUsernameFormComponent(),
                        $this->getEmailFormComponent(),
                        $this->getPasswordFormComponent(),
                        $this->getPasswordConfirmationFormComponent(),
                    ])
                    ->statePath('data'),
            ),
        ];
    }

    protected function getNameFormComponent(): Component
    {
        return TextInput::make('name')
            ->label('昵称或姓名')
            ->required()
            ->maxLength(255)
            ->autofocus();
    }

    protected function getUsernameFormComponent(): Component
    {
        return TextInput::make('username')
            ->label('用户名(通常是数字和字母的组合)')
            ->required()
            ->maxLength(255)
            ->unique($this->getUserModel());
    }

    protected function mutateFormDataBeforeRegister(array $data): array
    {
        if(!empty($this->refer)){
            $user = User::where('referral_code', $this->refer)->first();
            if($user){
                $data['referred_by'] = $user->id;
                User::find($user->id)->increment('referrals_count');
            }
        }
        $data['referral_code'] = strtolower(Str::random(12));
        return $data;
    }
}

